package main

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
)

type User struct {
	gorm.Model
	// 通过标签，将外键定义为：UserRefer
	CreditCards []CreditCard `gorm:"foreignkey:UserRefer"`
}

type CreditCard struct {
	gorm.Model
	Number    string
	UserRefer uint // 新定义的外键名
}

func Mysqlinit()  (db *gorm.DB) {
	fmt.Print("My init DB")
	dsn := "root:root@tcp(192.168.42.200:3306)/portscan?charset=utf8mb4"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("err")
	}
	return db
}

func My_first_table(db *gorm.DB)  {
	fmt.Println("My_first_table   create table Product ")
	// Migrate the schema
}

func My_first_table_CreditCard(db *gorm.DB)  {
	fmt.Println("My_first_table   create table Product ")
	// Migrate the schema
	db.AutoMigrate(&User{})
	db.AutoMigrate(&CreditCard{})

	card := CreditCard {
		Number:"string",
		UserRefer:'uint' // 新定义的外键名
	}
	db.Create(&card)

	//u := User{
	//	Username:"tizi365",
	//	Password:"123456",
	//	CreateTime:time.Now().Unix(),
	//}
	//
	////插入一条用户数据
	////下面代码会自动生成SQL语句：INSERT INTO `users` (`username`,`password`,`createtime`) VALUES ('tizi365','123456','1540824823')
	//
	//db.Create(&u)
}

func check_my_card(db *gorm.DB)  {
	user := User{}
	// 查询用户数据
	//自动生成sql： SELECT * FROM `users`  WHERE (username = 'tizi365') LIMIT 1
	db.Where("username = ?", "tizi365").First(&user)
	fmt.Println(user)

	//自动生成SQL： SELECT * FROM emails WHERE user_id = 111; // 111 是user的主键ID值
	// 关联查询的结果，保存到user.CreditCard属性
	//db.Model(&user).Association("CreditCard").Find(&user.CreditCard)

}

func main() {
// refer https://github.com/go-sql-driver/mysql#dsn-data-source-name for details
//dsn := "user:pass@tcp(192.168.42.200:3306)/portscan?charset=utf8mb4&parseTime=True&loc=Local"
dsn := "root:root@tcp(192.168.42.200:3306)/portscan?charset=utf8mb4"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})

if err != nil {
	fmt.Println("err")
}
if db != nil {
	fmt.Println("db")
}
Mydb := Mysqlinit()
My_first_table_CreditCard(Mydb)
check_my_card(Mydb)
}



